package com.gitee.chili.leisure.server;

import com.gitee.chili.leisure.core.Packet;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * 消息编码器
 */
@Slf4j
public class MessageEncoder extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if (!(msg instanceof Packet)) {
            super.write(ctx, msg, promise);
            return;
        }

        Packet packet = (Packet) msg;


        ByteBuf byteBuf = ctx.alloc().buffer();
        // 写出消息长度, 目前写出 0 只是为了占位
        byteBuf.writeShort((short) 0);
        // 写出消息编号
        byteBuf.writeShort((short) packet.getCmd().getNumber());
        // 写出消息体
        byteBuf.writeBytes(packet.getBody());

        BinaryWebSocketFrame frame = new BinaryWebSocketFrame(byteBuf);
        super.write(ctx, frame, promise);
    }
}
